package org.newbee.des.zookeeper.client;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.Comparator;
import java.util.List;

/**
 * Created by yujie on 2016/10/18.
 */
public class ZKClient1 {

    private static ZooKeeper zooKeeper;

    public static void main(String[] args) {
        try {
            zooKeeper = new ZooKeeper("localhost", 2181, watchedEvent -> {
                System.out.println(watchedEvent.getType());
                if (watchedEvent.getType().equals(Watcher.Event.EventType.NodeChildrenChanged)) {
                    a(watchedEvent.getPath());
                }
            });
            Stat stat = zooKeeper.exists("/zk", false);
            if (null == stat) {
                zooKeeper.create("/zk", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            } else {
                System.out.println(stat.getVersion());
            }

            zooKeeper.create("/zk/client", "client1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

            a("/zk");

            while (true) {
                System.out.println("检测");
                zooKeeper.getChildren("/zk", true);
                Thread.sleep(500);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void a(String path) {
        try {
            List<String> list = zooKeeper.getChildren(path, false);
            if (null == list || list.size() == 0) {
                System.out.println("无任何节点");
                return;
            }
            String node = list.stream().sorted(Comparator.comparing(Object::toString)).findFirst().get();
            System.out.println("===" + node);
            byte[] data = zooKeeper.getData(path + "/" + node, false, null);
            System.out.println(new String(data));
            if ("client1".equals(new String(data))) {
                System.out.println("我可以运行");
            } else {
                System.out.println("我不能运行");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
